forked from nottherealironman/Study-progress-monitor-system
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.java
402 lines (369 loc) · 14.5 KB
/
Server.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
import java.net.*;
import java.io.*;
import java.util.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyAgreement;
import javax.crypto.NoSuchPaddingException;
import java.util.stream.*;
public class Server {
private static int clientCount;
private final KeyPairGenerator keyPairGen;
private final PrivateKey privateKey;
private final PublicKey publicKey;
public Server() throws NoSuchAlgorithmException {
keyPairGen = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGen.genKeyPair();
this.privateKey = keyPair.getPrivate();
this.publicKey = keyPair.getPublic();
}
public PrivateKey getPrivateKey() {
return this.privateKey;
}
public PublicKey getPublicKey() {
return publicKey;
}
public KeyPairGenerator getKeyPairGen() {
return keyPairGen;
}
public String decrypt(byte [] encodedMessage) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey, cipher.getParameters());
return new String(cipher.doFinal(encodedMessage));
}
public static void main (String args[]) {
try{
// Initilizing server port
int serverPort = 8888;
// Creating socket to communicate with client
ServerSocket listenSocket = new ServerSocket(serverPort);
int i=0;
Server tcpServer = new Server();
PublicKey publicKey = tcpServer.getPublicKey();
System.out.println("Server started");
while(true) {
// Creating socket to listen to client request
Socket clientSocket = listenSocket.accept();
clientCount++;
// Connection class to create threads to handle multiple clients
Connection c = new Connection(clientSocket, i++,clientCount, publicKey, tcpServer.getPrivateKey());
}
} catch(IOException e) {System.out.println("Listen socket:"+e.getMessage());}
catch (NoSuchAlgorithmException e){ System.out.println("Algorithm: "+ e.getMessage()); }
}
}
class Connection extends Thread {
// Declaration of classes, variables, list and streams
ObjectInputStream inObj;
ObjectOutputStream outObj;
DataInputStream inData;
DataOutputStream outData;
Socket s;
int thrdn;
int clientCount;
DatabaseUtility dataObj = new DatabaseUtility();
LinkedList<Subject> subjResult;
LinkedList<Student> studResult;
LinkedList<Grade> grdResult;
LinkedList<GradedAssessment> stdGrd;
LinkedList<String> menuList;
SubjectList subjList;
StudentList studList;
GradeList grdList;
GradedAssessment grdAssmnt;
HashMap<String, String> request;
String orgRequest;
boolean dbStatus;
String requestType;
String printMsg;
PublicKey publicKey;
PrivateKey privateKey;
HashMap<String, String> RegInfo = new HashMap<String, String>();
HashMap<String, String> LogInfo = new HashMap<String, String>();
HashMap<String, String> response;
public Connection (Socket aClientSocket, int tn, int client,PublicKey key, PrivateKey privateKey) {
publicKey =key;
this.privateKey = privateKey;
try {
thrdn=tn;
clientCount =client;
s = aClientSocket;
// Initializing Input and Output object stream to communicate with clients
inObj = new ObjectInputStream(s.getInputStream());
outObj =new ObjectOutputStream(s.getOutputStream());
inData = new DataInputStream(s.getInputStream());
outData =new DataOutputStream(s.getOutputStream());
System.out.println("Client count: "+client);
// Calling start method of thread to handle client request
this.start();
} catch(IOException e) {System.out.println("Connection:"+e.getMessage());}
}
public String decrypt(byte [] encodedMessage) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey, cipher.getParameters());
return new String(cipher.doFinal(encodedMessage));
}
public void run(){
try {
System.out.printf("Thread %d for Client %d\n",thrdn, clientCount);
// Method to create and populate tables automatically
dataObj.createDBtables();
// Parse request from client
while ((request= (HashMap) inObj.readObject())!=null){
// Fetch the type of request send by client
requestType = request.get("type");
// Use switch case statement to perform database query to handle appropriate request
switch(requestType){
case "hello":
// Register
if(request.get("LoginType") != null && request.get("LoginType").equals("1")){
if(request.get("UserName") != null && RegInfo.get("UserName") == null) {
int statusId;
if(RegInfo.get("userType").equals("2")) {
// vertify unique student
statusId = dataObj.vertifyExsitingStu(request.get("UserName"));
} else {
statusId = dataObj.vertifyExsitingAdmin(request.get("UserName"));
}
// -1 user not existed;
if(statusId == -1) {
outData.writeUTF("Sorry, the User does not exist");
outData.writeInt(0);
break;
} else if(statusId == 0) {
outData.writeUTF("Sorry, the User is already registered. Please, login");
outData.writeInt(0);
break;
}
RegInfo.put("fullName",request.get("UserName"));
outData.writeUTF("Please type your password");
//generate the encoded key
byte[] bytesPubKey = publicKey.getEncoded();
System.out.println("PublicKey size in bytes: " +bytesPubKey.length);
//send the keysize;
outData.writeInt(bytesPubKey.length);
//send the key in bytes
outData.write(bytesPubKey, 0, bytesPubKey.length);
break;
} else if(request.get("userType") != null){
RegInfo.put("userType",request.get("userType"));
outData.writeUTF("Please type your name:");
break;
}
outData.writeUTF("Please select user type:\n 1. Administrator\n 2. Student");
break;
}
// Login
else if (request.get("LoginType") != null && request.get("LoginType").equals("2")){
if(request.get("UserId") != null) {
// verify if user is registered or not
int statusId;
if(LogInfo.get("userType").equals("2")) {
// vertify unique student
statusId = dataObj.vertifyExsitingStuById(Integer.parseInt(request.get("UserId")));
} else {
statusId = dataObj.vertifyExsitingAdminById(Integer.parseInt(request.get("UserId")));
}
// -1 user not exist;
if(statusId == -1) {
outData.writeUTF("Sorry, the entered UserId does not exist");
outData.writeInt(0);
break;
} else if(statusId == 1) {
outData.writeUTF("Sorry, the User is not registered");
outData.writeInt(0);
break;
}
LogInfo.put("UserId",request.get("UserId"));
outData.writeUTF("Please type your password");
//generate the encoded key
byte[] bytesPubKey = publicKey.getEncoded();
System.out.println("PublicKey size in bytes: " +bytesPubKey.length);
//send the keysize;
outData.writeInt(bytesPubKey.length);
//send the key in bytes
outData.write(bytesPubKey, 0, bytesPubKey.length);
break;
}
else if(request.get("userType") != null){
LogInfo.put("userType",request.get("userType"));
outData.writeUTF("Please, Enter your User Id:");
break;
}
outData.writeUTF("Please select user type:\n 1. Administrator\n 2. Student");
break;
}
printMsg = "1. User registration\n2. Login";
outData.writeUTF(printMsg);
break;
case "register":
int msgLength = inData.readInt();
//read the size of encrypted message to be sent from client
byte [] encodedmessage = new byte [msgLength];
//read the encryped password sent from client
inData.read(encodedmessage,0, encodedmessage.length);
RegInfo.put("password",decrypt(encodedmessage));
int userId = dataObj.userRegister(RegInfo);
if(userId > 0){
outData.writeUTF("Registration successed\n Your ID is: " + userId);
} else {
outData.writeUTF("Registration failed");
}
break;
case "login":
int logMsgLength = inData.readInt();
//read the size of encrypted message to be sent from client
byte [] logEncodedmessage = new byte [logMsgLength];
//read the encryped password sent from client
inData.read(logEncodedmessage,0, logEncodedmessage.length);
LogInfo.put("password",decrypt(logEncodedmessage));
String userName = dataObj.userLogin(LogInfo);
HashMap<String, String> loginResponse = new HashMap<String, String>();
// Send response to client
if(userName != null){
loginResponse.put("status","success");
loginResponse.put("message","Logged in successfully");
loginResponse.put("userName",userName);
} else {
loginResponse.put("status","fail");
loginResponse.put("message","Invalid login credentials. Please, try again");
}
outObj.writeObject(loginResponse);
break;
case "view-assessment-request":
// calling database method to fetch subjects
subjResult = dataObj.fetchSubjectList();
// Storing list of subjects in SubjectList
subjList = new SubjectList(subjResult);
// sending the response to client
outObj.writeObject(subjList);
break;
case "student-list-request":
synchronized(this.getClass()){
// calling database method to fetch students
studResult = dataObj.fetchStudentList();
// Storing list of students in StudentList
studList = new StudentList(studResult);
// sending the response to client
outObj.writeObject(studList);
break;
}
case "grade-list-request":
// calling database method to fetch grades
grdResult = dataObj.fetchGradeList();
// Storing list of grades in GradeList
grdList = new GradeList(grdResult);
// sending the response to client
outObj.writeObject(grdList);
break;
case "view-student-grade-request":
// calling database method to fetch student grade
stdGrd = dataObj.fetchStudentGrade(Integer.parseInt(request.get("studentID")), Integer.parseInt(request.get("subjectID")));
// sending the response to client
outObj.writeObject(stdGrd);
break;
case "set-grade-request":
// calling database method to insert student grade in database
dbStatus = dataObj.insertStudentGrade(Integer.parseInt(request.get("studentID")), Integer.parseInt(request.get("subjectID")), request.get("assessmentID"), Integer.parseInt(request.get("gradeID")));
// Creating response of HashMap type to sent to client
HashMap<String, String> response = new HashMap<String, String>();
// if student grade is inserted successfully the send success status to client else send fail status
if(dbStatus){
response.put("status","success");
}
else{
response.put("status","fail");
}
// sending the response to client
outObj.writeObject(response);
break;
case "add-student-request":
synchronized(this.getClass()){
// Creating response of HashMap type to send to client
HashMap response1 = new HashMap();
boolean caper = false;
// calling database method to fetch students
studResult = dataObj.fetchStudentList();
// Iterate through list of students, verify new student do no exist already ;
// lambda expression in filter checks if object exists
// streams return obj if found or else null
Student std = studResult.stream()
.filter(e -> e.getFullName().equalsIgnoreCase(request.get("name").trim()))
.findFirst()
.orElse(null);
// student name found in list
if(std!=null) {
System.out.println("Student already exists.");
response1.put("status","fail");
response1.put("reason","student name already exists");
response1.put("data",std.getFullName());
caper=true;
}
if (!caper) {
// calling database method to insert new student into a database
dbStatus = dataObj.insertNewStudent(request.get("name").trim(), Integer.parseInt(request.get("year").trim()));
// if student grade is inserted successfully then send success status to client else send fail status
if(dbStatus){
response1.put("status","success");
response1.put("data",request.get("name").trim());
} else{
response1.put("status","fail");
response1.put("reason","something went wrong while performing db insert");
response1.put("data",request.get("name"));
}
}
// sending the response to client
outObj.writeObject(response1);
break;
}
}
}
}
// Catch end of file exception
catch (EOFException e){
System.out.println("EOF:"+e.getMessage());
}
// Catch input/output exception
catch(IOException e) {
System.out.println("readline:"+e.getMessage());
}
// Catch class not found exception
catch(ClassNotFoundException ex){
ex.printStackTrace();
}
catch (NoSuchAlgorithmException e){
System.out.println("Algorithm: "+ e.getMessage());
}
catch (NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e){
System.out.println("invalid key spec: "+ e.getMessage());
}
catch (InvalidKeyException e){
System.out.println("invalid key: "+ e.getMessage());
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
s.close();
}
catch (IOException e){
/*close failed*/}
}
}
}