-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
539 lines (479 loc) · 19.7 KB
/
Client.java
File metadata and controls
539 lines (479 loc) · 19.7 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
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.ser.Serializers;
import Requests.*;
import Event.Event;
import JSON.WriteJsonObject;
import Responses.Response;
public class Client {
public static void main(String[] args) {
try {
WriteJsonObject json = new WriteJsonObject(); // Serializer and Deserializer object
Scanner scan = new Scanner(System.in); // Scanner for client input
ArrayList<Event> EVENTS = new ArrayList<Event>(); // List of all Events from the database
DatagramSocket server; // Send and recieves packets
InetAddress Ip; // the server's Ip should stay the same when running
byte buf[]; // Storage for the json string
int port; // Port number should also stay the same
// GETS THE PLACE TO SEND THE DATA TO
while (true) {
try {
server = connectToServer(); // Method prompts for host ip and port
Ip = InetAddress.getByName(getHost());
buf = null;
port = getPort();
break;
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
// MAIN LOGIC LOOP
while (true) {
// User is prompted for an action
System.out.printf(
"%-4s %-30s%n%-4s %-30s%n%-4s %-30s%n%-4s %-30s%n%-4s %-30s%n%-4s %-30s\n> ",
"(1):", "List the current events", "(2):", "Create a new event", "(3):", "Donate to an event",
"(4):", "Update an event", "(5):", "List ALL events", "(q):", "Quit");
String answer = scan.nextLine();
// LIST CURRENT EVENTS
if (answer.startsWith("1")) {
EVENTS = getEvents(server, buf, Ip, port, json);
EVENTS = currentEvents(EVENTS);
listEvents(EVENTS);
System.out.println();
}
// CREATE A NEW EVENT
else if (answer.startsWith("2")) {
CreateEventRequest newEvent = formEvent();
createEvent(newEvent, server, buf, Ip, port, json);
}
// DONATE AN AMOUNT TO AN EVENT
else if (answer.startsWith("3")) {
EVENTS = getEvents(server, buf, Ip, port, json);
donateToEvent(EVENTS, server, buf, Ip, port, json);
}
// UPDATES AN EVENT FROM ALL EVENTS
else if (answer.startsWith("4")) {
EVENTS = getEvents(server, buf, Ip, port, json);
listEvents(EVENTS);
updateEvent(EVENTS, server, buf, Ip, port, json);
}
// PRINTS OUT CURRENT EVENTS AND PAST EVENTS
else if (answer.startsWith("5")) {
EVENTS = getEvents(server, buf, Ip, port, json);
listAllEvents(EVENTS);
System.out.println();
}
// QUITS THE PROGRAM
else if (answer.toLowerCase().startsWith("q")) {
break;
}
// INVALID INPUT DETECTED, TRY AGAIN
else {
System.out.println("Invalid input.");
}
}
// Always close the connection when done
server.close();
} catch (Exception e) {
System.err.println(e);
}
}
// -------------------------------------------------------------------------------------------------------------------------------------//
// -------------------------------------------------------------------------------------------------------------------------------------//
/**
* Gets the active events from all events
*/
private static ArrayList<Event> currentEvents(ArrayList<Event> EVENTS) {
return EVENTS
.stream()
.filter(event -> !event.hasEnded())
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* Gets the past events from all events
*/
private static ArrayList<Event> pastEvents(ArrayList<Event> EVENTS) {
return EVENTS
.stream()
.filter(Event::hasEnded)
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* Sends information to create a new event
*/
private static void createEvent(CreateEventRequest newEvent, DatagramSocket server,
byte buf[], InetAddress Ip, int port,
WriteJsonObject json) {
try {
// Send to server
String body = json.serialize(newEvent);
buf = (json.serialize(new Request(RequestType.CREATE, body))).getBytes();
DatagramPacket DpSend = new DatagramPacket(buf, buf.length, Ip, port);
server.send(DpSend);
// Recieve from server
byte[] recieve = new byte[65535];
DatagramPacket DpRecieve = new DatagramPacket(recieve, recieve.length);
server.receive(DpRecieve);
// Deserialize packet data
Response response = json.deserialize(data(recieve).toString(), Response.class);
} catch (Exception e) {
System.err.println(e);
}
}
/**
* Creates a new Event object to be sent
*/
private static CreateEventRequest formEvent() {
Scanner scan = new Scanner(System.in);
String title = null;
String description = null;
double target = -1;
String deadline = null;
try {
while (title == null) {
System.out.print("Enter the title for Event: ");
title = scan.nextLine();
}
while (description == null) {
System.out.print("Enter the description for the Event: ");
description = scan.nextLine();
}
while (target < 0) {
System.out.print("Enter the target amount as a double (####.##): ");
String temp = scan.nextLine();
Scanner tempScan = new Scanner(temp);
if (tempScan.hasNextDouble())
target = tempScan.nextDouble();
}
while (deadline == null) {
System.out.println(
"Enter the deadline in the form YYYY-MM-DDTHH:MM:ss.SSSZ\ne.g. Oct 25, 2023 at 1:45:30.30PM would be 2023-10-25T13:45:30.300Z: ");
deadline = scan.nextLine();
}
return (new CreateEventRequest(title, description, target, deadline));
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
}
}
/**
* tries to connect to the server
*/
private static DatagramSocket connectToServer() {
try {
return new DatagramSocket();
} catch (Exception e) {
System.err.println(e.getMessage());
}
return null;
}
/**
* helper method of connectToServer to prompt the client for a server host
*/
private static String getHost() {
Scanner scan = new Scanner(System.in);
System.out.print("Enter IP address: ");
try {
String host = scan.nextLine();
return host;
} catch (Exception e) {
System.err.println(e);
}
return null;
}
/**
* helper method of connectToServer to prompt the client for a port number
*/
private static int getPort() {
Scanner scan = new Scanner(System.in);
System.out.print("Enter port number: ");
try {
int port = scan.nextInt();
return port;
} catch (Exception e) {
System.err.println(e);
}
return 6789;
}
/**
* gets all events from server and returns them as an ArrayList
*/
private static ArrayList<Event> getEvents(DatagramSocket server, byte buf[], InetAddress Ip, int port,
WriteJsonObject json) {
ArrayList<Event> events = new ArrayList<Event>();
try {
// Send to server
buf = (json.serialize(new Request(RequestType.EVENTS, json.serialize(new EventsRequest()))))
.getBytes();
DatagramPacket DpSend = new DatagramPacket(buf, buf.length, Ip, port);
server.send(DpSend);
// Recive from server
byte[] recieve = new byte[65535];
DatagramPacket DpRecieve = new DatagramPacket(recieve, recieve.length);
server.receive(DpRecieve); // Waits for packet from server
// Deserialize packet data
Response response = json.deserialize(data(recieve).toString(),
Response.class);
if (response.responseType == RequestType.EVENTS)
events = json.deserialize(response.responseBody, new TypeReference<ArrayList<Event>>() {
});
} catch (Exception e) {
System.err.println(e.getMessage());
}
events = sortDeadline(events);
return events;
}
/**
* Makes byte array into string
*/
public static StringBuilder data(byte[] a) {
if (a == null)
return null;
StringBuilder ret = new StringBuilder();
int i = 0;
while (a[i] != 0) {
ret.append((char) a[i]);
i++;
}
return ret;
}
/**
* lists all the current events and prompts user to choose one
*/
private static void updateEvent(ArrayList<Event> EVENTS, DatagramSocket server, byte buf[], InetAddress Ip,
int port, WriteJsonObject json) {
Scanner scan = new Scanner(System.in);
try {
System.out.println("choose an event or -1 to go back: ");
int index = scan.nextInt() - 1;
if (index < EVENTS.size() && index >= 0) {
Event newEvent = EVENTS.get(index);
String update = changeEvent(newEvent, json);
// Send to server
buf = (json.serialize(new Request(RequestType.UPDATE, update))).getBytes();
DatagramPacket DpSend = new DatagramPacket(buf, buf.length, Ip, port);
server.send(DpSend);
// Recive from server
byte[] recieve = new byte[65535];
DatagramPacket DpRecieve = new DatagramPacket(recieve, recieve.length);
server.receive(DpRecieve);
// Deserialize packet data
Response response = json.deserialize(data(recieve).toString(),
Response.class);
} else if (index == -2) {
} else {
System.out.println("That index is not available.");
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
/**
* Prompts the user to pick an event and donates money to it
*/
private static void donateToEvent(ArrayList<Event> EVENTS, DatagramSocket server, byte buf[], InetAddress Ip,
int port, WriteJsonObject json) {
Scanner scan = new Scanner(System.in);
try {
ArrayList<Event> curEvents = currentEvents(EVENTS);
listEvents(curEvents);
int index = -2;
String temp;
while (index < -1) {
System.out.print("Choose and active event or 0 to go back: ");
temp = scan.nextLine();
Scanner scanTemp = new Scanner(temp);
if (scanTemp.hasNextInt())
index = scanTemp.nextInt() - 1;
}
if (index >= 0 && index < curEvents.size()) {
double amount = -1.0;
while (amount < 0) {
System.out.print("Enter a donation amount (####.##): ");
temp = scan.nextLine();
Scanner scanTemp = new Scanner(temp);
if (scanTemp.hasNextDouble())
amount = scanTemp.nextDouble();
}
String donate = json.serialize(new DonateRequest(curEvents.get(index).getId(), amount));
// Send to server
buf = (json.serialize(new Request(RequestType.DONATE, donate))).getBytes();
DatagramPacket DpSend = new DatagramPacket(buf, buf.length, Ip, port);
server.send(DpSend);
} else if (index == -1) {
return;
} else {
System.out.println("That index is not available.");
}
// Recieve from server
byte[] recieve = new byte[65535];
DatagramPacket DpRecieve = new DatagramPacket(recieve, recieve.length);
server.receive(DpRecieve);
// Deserialize packet data
Response response = json.deserialize(data(recieve).toString(), Response.class);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
/**
* Prints current variables and prompts for new variable
*/
private static String changeEvent(Event event, WriteJsonObject json) {
Scanner scan = new Scanner(System.in);
String title = null;
while (title == null) {
System.out.printf("Current Title: %25s%n", event.getTitle());
System.out.print("New Title: ");
title = scan.nextLine();
}
if (!title.isEmpty())
event.setTitle(title);
String description = null;
while (description == null) {
System.out.printf("Current Description: %s%n", event.getDescription());
System.out.print("New Description: ");
description = scan.nextLine();
}
if (!description.isEmpty())
event.setDescription(description);
double target = -1.0;
String temp = "";
while (target < 0) {
System.out.printf("Current Target: %-15s%n", getCurrency(event.getTarget()));
System.out.print("New Target: ");
temp = scan.nextLine();
Scanner scantemp = new Scanner(temp);
if (temp.isEmpty()) {
break;
}
if (scantemp.hasNextDouble())
target = scantemp.nextDouble();
}
if (!temp.isEmpty())
event.setGoal(target);
double balance = -1.0;
while (balance < 0) {
System.out.printf("Current Balance: %-15s%n", getCurrency(event.getBalance()));
System.out.print("New Balance: ");
temp = scan.nextLine();
Scanner scantemp = new Scanner(temp);
if (temp.isEmpty()) {
break;
}
if (scantemp.hasNextDouble())
balance = scantemp.nextDouble();
}
if (!temp.isEmpty())
event.setCurrentPool(balance);
String date = null;
while (date == null) {
System.out.printf("Current Date: %-20s%n", event.getDeadlineString());
System.out.print("New Date (YYYY-MM-DDTHH:MM:ss.SSSZ): ");
date = scan.nextLine();
}
if (!date.isEmpty())
event.setEndDate(date);
return json.serialize(event);
}
/**
* helper method of chooseEvent that lists all events
*/
private static void listEvents(ArrayList<Event> events) {
int i = 1;
for (Event event : events) {
System.out.printf(
"%8d. %-35s Ends: %-12s%n = %-1s =%n----------------------------------------------------%n",
i++, event.getTitle(), event.getDeadlineString().substring(0, 10), event.getDescription());
}
}
/**
* Prints all events, past and current, in a table
*/
private static void listAllEvents(ArrayList<Event> EVENTS) {
ArrayList<Event> curEvents = currentEvents(EVENTS);
ArrayList<Event> pastEvents = pastEvents(EVENTS);
System.out.println(
"--------------------------------------------------------------------------|=|--------------------------------------------------------------------------");
System.out.printf("| %-25s | %-15s | %-8s | %-12s |=| %-25s | %-15s | %-8s | %-12s |%n", "Current Events",
"Target", "Percent", "Deadline", "Past Events", "Target", "Percent", "Deadline");
System.out.println(
"--------------------------------------------------------------------------|=|--------------------------------------------------------------------------");
for (int i = 0; i < curEvents.size() || i < pastEvents.size(); i++) {
String ce = "";
String cet = "";
String cep = "";
String ced = "";
String pe = "";
String pet = "";
String pep = "";
String ped = "";
if (i < curEvents.size()) {
ce = curEvents.get(i).getTitle();
cet = getCurrency(curEvents.get(i).getTarget());
cep = getPercent(curEvents.get(i).getTarget(), curEvents.get(i).getBalance());
ced = curEvents.get(i).getDeadlineString().substring(0, 10);
}
if (i < pastEvents.size()) {
pe = pastEvents.get(i).getTitle();
pet = getCurrency(pastEvents.get(i).getTarget());
pep = getPercent(pastEvents.get(i).getTarget(), pastEvents.get(i).getBalance());
ped = pastEvents.get(i).getDeadlineString().substring(0, 10);
}
System.out.printf("| %-25s | %-15s | %-8s | %-12s |=| %-25s | %-15s | %-8s | %-12s |%n", ce, cet, cep,
ced, pe, pet, pep, ped);
System.out.println(
"--------------------------------------------------------------------------|=|--------------------------------------------------------------------------");
}
System.out.println();
}
/**
* gets the percent completeness of an event and returns it as a String with 2
* decimal places
*/
private static String getPercent(double target, double balance) {
double percent = (balance / target);
NumberFormat percentage = NumberFormat.getPercentInstance();
return percentage.format(percent);
}
/**
* gets the currency formatted String of a value
*/
private static String getCurrency(double value) {
DecimalFormat currency = new DecimalFormat("$###,##0.00");
return currency.format(value);
}
/**
* Sorts ArrayList based on deadline
*/
private static ArrayList<Event> sortDeadline(ArrayList<Event> array) {
int soonest, times;
times = array.size();
ArrayList<Event> temp = new ArrayList<Event>();
if (array.isEmpty())
return temp;
for (int i = 0; i < times; i++) {
if (array.size() <= 1) {
temp.add(array.get(0));
} else {
soonest = 0;
for (int j = 1; j < array.size(); j++) {
if (array.get(j).getDeadline().compareTo(array.get(soonest).getDeadline()) <= 0) {
soonest = j;
}
}
temp.add(array.remove(soonest));
}
}
return temp;
}
}